<?php
namespace Api\Controller;
use Common\Controller\ApiController;
use Common\ORG\PublicFunction;
use Common\ORG\WxFunction;


/**

 * 用户信息获取验证

 *

 * 用户登陆和token信息获取。

 * @Author      LD(191696242@qq.com)

 * @Version     1.o

 * @Date        2020/12/15

 * @Time        16:00

 * @since

 */
class IndexController extends ApiController{


    public function _initialize() {

        $getsecret  = $_SERVER['HTTP_APPSECRET'];
        //取head标签内容
        if(!preg_match('/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/', $getsecret)){
            $this->ajaxReturn(1, 'appsecret格式错误');
        }

        if($this->appsecret <> $getsecret){
            $this->ajaxReturn(1, 'appsecret错误');
        }
        parent::_initialize();
    }


    /**

     * gettoken

     * 获取用户token信息

     * 获取用户token信息，用于所有接口数据的获取验证

     * @access public

     * @param int $uid (必填：是) 用户UID

     * @param string appsecret (必填：是) 应用secret，headers提交用于token数据的生成获取

     * @since

     * @return json

     */
    public function gettoken(){

        //$appid      = M('Members')->query('select uuid_short() as token'); //mysql计算用户UUID
        $uid        = I('uid', 0,'intval');
        if(empty($uid)){
            $this->ajaxReturn(1,'用户ID不能为空！');
        }

        $userinfo   = M('members')->where(['uid'=>$uid])->find();
        if(empty($userinfo)){
            $this->ajaxReturn(1, '用户信息不存在！');
        }

        $randStr    = PublicFunction::createNoncestr(6);//随机字符串

        $data       = array(
            'uid'       => $uid,
            'appkey'    => $this->appkey,
            'appsecret' => $this->appsecret,
            'randStr'   => $randStr
        );
        $options    = 0;//数据格式选项（可选）
        $iv         = '';//加密初始化向量（可选）
        $result = openssl_encrypt(json_encode($data), 'AES-128-CBC', $this->appsecret, $options, $iv); //AES-128-CBC加密方式

        S('uid_'.$uid, $result, 86400*2);
        $this->ajaxReturn(0, 'ok', ['token'=>$result]);
    }

    /**

     * sms

     * 短信获取

     * 用户登陆注册及其他场景短信获取

     * @access public

     * @param int $mobile (必填：是) 是否必填

     * @param int $num (必填：否) 每页显示条数 默认300条

     * @param int $order_type (必填：否) 订单时间查询类型(1：下单时间，2：完成时间，3：更新时间) 注:默认为2

     * @param int $times (必填：否) 拉取时间如:20181205 或 2018120516 或 201812051755 注:默认为查询最近5分钟的数据

     * @since

     * @return json

     */
    public function sms(){
        $this->ajaxReturn(0, 'ok');
    }

    /**

     * login

     * 用户登陆

     * 获取用户登陆数据，并返回用户登陆信息

     * @access public

     * @param int       $loginype (必填：是) 登陆类型 1、微信登陆 2、短信登陆 3、密码登陆

     * @param string    $mobile (必填：是) 用户账号 可能是用户名、手机号、邮箱

     * @param string    $password (选填：是) 用户密码

     * @param int       $mobileVcode (选填：否) 手机验证码

     * @param int       $userinfo (选填：否) 微信登陆用户信息

     * @since

     * @return json

     */
    public function login(){
        if(!IS_POST){
            $this->ajaxReturn(1, '提交方式错误！');
        }
        $loginType      = I('login_type', 0, 'intval');
        $mobile         = I('mobile');  //用户账号
        $password       = I('password');   //密码
        $mobileVcode    = I('mobile_vcode'); //手机验证码
        $userinfo       = I('userinfo');//微信登陆用户信息
        $mobile_mod     = D('Members');
        if(!in_array($loginType, [1,2,3])){
            $this->ajaxReturn(1,'登陆类型错误');
        }
        if($loginType==1) {
            //微信登陆

            if(empty($userinfo['code']) || empty($userinfo['encryptedData']) || empty($userinfo['iv'])){
                $this->ajaxReturn(1, '登陆信息错误');
            }

            $response = WxFunction::getOauthOrization($userinfo['code']);
            if ($response == false && empty($response['data']['session_key'])) {
                $this->ajaxReturn(1, '微信sessionkey换取失败');
            }
            /*$userinfo   = array(
                'encryptedData'=> "d4EUUpN9k9UaFW4FL9TFUbVjAtV2/+qpkIxCEOAoFR9/T7PaFshPcoCZZKcCrNbsmOxRZfVOhX8Zzgi9tuHg+CwfRrN0zWEF05gVH8zlQOp2LOVyLKLbSXG04Ur78IjOACbFG1K5yXiVDYvMysaHqnTQQSuZcHnIciGxgzk0PIAPm4NRa7KB9DfGYh6jyJG+0hcKoREotfeLTOR0VDXIMl6O7ottRn330dzbLBtO7dEJPgMwDFWQTgIzT2V4PP0PbMRDCw885CE7l6xmwvpqhMRhQpALg0fPmqkr6TjuhpNSxv/g/FLe8APkZ+A7di+ViOkP2VbuLGvbQe9iCgJ0JsHzNT3q3W7S7A0FCXk+tEt3+XlEJcjW2P44Yjy9LSVeyO3vymrzerU7O6a8z5+gwjH9UXedkwS5u1iIc+7EZfaXk2G0cIveISI5XjPYzGMkf/5KrnMXZ8xmZDcpNmtaluAlGg+WiP1Oi6aw0yWD7bw=",
                'iv'=>"OhgM18eYNSdNe2T3VRkXBA=="
            );*/
            $data = array();
            $errCode = WxFunction::decryptData($userinfo['encryptedData'], $userinfo['iv'], $response['data']['session_key'], $data);
            $data = get_object_vars(json_decode($data));
            if ($errCode == false || empty($data['openId'])) {
                $this->ajaxReturn(1, '获取用户信息失败');
            }
            $mb = M('MembersBind')->where(['openid'=>$data['openId']]);
            if(!$mb){
                $this->ajaxReturn(1, '微信绑定信息不存在');//用户不存在
            }
            $check_map['uid'] = array('eq',$mb['uid']);
        } elseif($loginType==2) {
            //短信登陆

            if(empty($mobile) || empty($mobileVcode)){
                $this->ajaxReturn(1, '登陆信息错误');
            }

            if (!fieldRegex($mobile,'mobile')) {
                $this->ajaxReturn(1, '手机格式错误');
            }
            $sms   = S('login_'.$mobile);
            if(!$sms){
                $this->ajaxReturn(1, '验证码不存在或已过期');
            }

            if($sms <> $mobileVcode){
                $this->ajaxReturn(1, '手机验证码错误');
            }
            S('login_'.$mobile, '');
            $check_map['mobile'] = array('eq',$mobile);
        }else{
            //密码登陆

            if(empty($mobile) || empty($password)){
                $this->ajaxReturn(1, '登陆信息错误');
            }
            $account_type='username';
            if (fieldRegex($mobile,'email'))
            {
                $account_type='email';
            }elseif (fieldRegex($mobile,'mobile')) {
                $account_type='mobile';
            }
            $check_map[$account_type] = array('eq',$mobile);
        }

        if(!$user = $mobile_mod->where($check_map)->find()) {
            $this->ajaxReturn(1, L('auth_null'));//用户不存在
        }

        if(!in_array($loginType,array(1, 2)) || !empty($password)) {
            $pwd = $mobile_mod->make_md5_pwd($password, $user['pwd_hash']);
            if ($pwd <> $user['password']) {
                $this->ajaxReturn(1, L('auth_password_failed'));//密码错误
            }
        }

        if($user['status'] == 2){
            $this->ajaxReturn(1, L('account_disabled'));//停用
        }elseif($user['status'] == 0){
            $this->ajaxReturn(1, L('auth_activation'));//未激活
        }

        unset($user['password']);

        //登陆日志
        write_members_log($user,'login','用户登录','小程序');

        $this->ajaxReturn(0, 'ok', $user);

    }


    /**

     * register

     * 用户注册

     * 提交用户数据数据，并返回用户注册信息

     * @access public

     * @param int       $loginype (必填：是) 登陆类型 1、微信登陆 2、短信登陆 3、密码登陆

     * @param string    $mobile (必填：是) 用户账号 可能是用户名、手机号、邮箱

     * @param string    $password (选填：是) 用户密码

     * @param int       $mobileVcode (选填：否) 手机验证码

     * @param int       $userinfo (选填：否) 微信登陆用户信息

     * @since

     * @return json

     */
    public function register() {
        if (C('qscms_closereg')) {
            $this->ajaxReturn(0, '网站暂停会员注册，请稍后再次尝试！');
        }

        if(!IS_POST){
            $this->ajaxReturn(1, '提交方式错误！');
        }

        //$utype          = I('post.utype', 0, 'intval');
        $mobile         = I('get.mobile', '', 'trim');
        $mobileVcode    = I('post.mobile_vcode', 0, 'intval');
        $email          = I('get.email', '', 'trim');
        $password       = I('get.password', '', 'trim');
        $passwordVerify = I('post.passwordVerify', '', 'trim');
        $userinfo       = I('userinfo');//微信登陆用户信息
        $regVerify      = S('reg_'.$mobile); //获取缓存注册手机验证码

        if(!$regVerify){
            $this->ajaxReturn(1, '验证码已过期！');
        }
        if($regVerify <> $mobileVcode){
            $this->ajaxReturn(1, '验证码错误！');
        }else{
            S('reg_'.$mobile, '');
        }

        if (empty($mobile) || !fieldRegex($mobile,'mobile')) {
            $this->ajaxReturn(1, '手机号码为空或格式错误！');
        }

        if (empty($email) || !fieldRegex($email,'email'))
        {
            $this->ajaxReturn(1, '邮件为空或格式错误！');
        }

        $user = M('Members')->where(['mobile'=>$mobile])->find();
        $email= M('Members')->where(['email'=>$email])->find();

        if(empty($user)) {
            if (empty($password) || empty($passwordVerify)) {
                $this->ajaxReturn(1, '密码或重复密码不能为空！');
            }

            if ($password <> $passwordVerify) {
                $this->ajaxReturn(1, '两次密码输入不一致！');
            }
        }



        if(!empty($userinfo['code']) && !empty($userinfo['encryptedData']) && !empty($userinfo['iv'])){
            $response = WxFunction::getOauthOrization($userinfo['code']);
            if ($response == false && empty($response['data']['session_key'])) {
                $this->ajaxReturn(1, '微信sessionkey换取失败');
            }

            $wxdata = array();
            $errCode = WxFunction::decryptData($userinfo['encryptedData'], $userinfo['iv'], $response['data']['session_key'], $wxdata);
            $wxdata = get_object_vars(json_decode($wxdata));
            if ($errCode == false || empty($data['openId'])) {
                $this->ajaxReturn(1, '获取用户信息失败');
            }

            $mb = M('MembersBind')->where(['type'=>'weixin', 'openid'=>$wxdata['openId']]);
            if($mb){
                $this->ajaxReturn(1, '该微信号已经绑定');
            }

            if(!empty($user) && !empty($email) && $user['uid']<>$email['uid']){
                $this->ajaxReturn(1, '输入的手机号和邮箱不是同一条记录');
            }

            if(empty($user) && empty($email)){
                //注册用户
                $res =$this->memberAdd($mobile, $password, $email);
            }

            //绑定微信账号
            $bind_user = array(
                'uid'           => $res['uid'],
                'type'          => 'weixin',
                'keyid'         => '',
                'info'          => json_encode($wxdata),
                'bindingtime'   => time(),
                'openid'        => $wxdata['openId'],
                'unionid'       => $wxdata['unionid']?:'',
                'is_bind'       => 1
            );

            M('MembersBind')->add($bind_user);

        }else {
            if ($user) {
                $this->ajaxReturn(1, '该手机号用户已经存在');
            }elseif ($email){
                $this->ajaxReturn(1, '邮件地址已经存在');
            }else{
                //注册用户
                $res = $this->memberAdd($mobile, $password, $email);
            }
        }

        $this->ajaxReturn(0, 'ok', $res);

    }


    /**

     * modifyUser

     * 修改用户类型

     * 修改用户类型

     * @access public

     * @param int       $uid (必填：是) 用户UID

     * @param string    $mobile (必填：是) 用户账号 可能是用户名、手机号、邮箱

     * @param string    $password (选填：是) 用户密码

     * @param int       $mobileVcode (选填：否) 手机验证码

     * @param int       $userinfo (选填：否) 微信登陆用户信息

     * @since

     * @return json

     */
    public function modifyUser(){
        $uid    = I('uid', 0, 'intval');
        $utype  = I('utype', 0, 'intval');
        if(!$uid){
            $this->ajaxReturn(1, '用户参数不能为空');
        }

        if(!$utype || !in_array($utype, array(1,2,3))){
            $this->ajaxReturn(1, '用户类型为空或超出范围');
        }

        $user = M('Members')->where(['uid'=>$uid])->find();
        if(!$user){
            $this->ajaxReturn(1, '修改的用户不存在');
        }

        $res = M('Members')->where(['uid'=>$user['uid']])->save(['utype'=> $utype]);
        if($res){
            $user = M('Members')->where(['uid'=>$uid])->find();
            $this->ajaxReturn(0, '用户类型更改成功', $user);
        }else {
            $this->ajaxReturn(1, '用户类型更改失败');
        }

    }

    //注册members表
    private function memberAdd($mobile, $password, $email){
        $data   = array(
            'utype'     => 0,
            'mobile'    => $mobile,
            'email'     => $email,
            'password'  => $password
        );
        $data   = $this->newName($data);    //添加用户名
        if(false === $res = $this->_local_add($data)){
            $this->ajaxReturn(1, '用户注册失败');
        }

        return $res;
    }





}
?>